# @Time    : 2023/12/22 21:25
# @Author  : 🍁
# @File    : account.py
# @Software: PyCharm

from django import forms
from django.core.exceptions import ValidationError
from django.db import models
from django.core import validators
from django.core.validators import RegexValidator
from django_redis import get_redis_connection

from .bootstrap import BootStrapForm
from ..models import User
from web.utils.scrypty import hash_password, check_password


class RegisterForms(BootStrapForm, forms.ModelForm):
    mobile = forms.CharField(label="手机号", max_length=11,
                             validators=[RegexValidator(r'^1[3-9]\d{9}$', "手机号格式"), ],
                             # widget=forms.TextInput(attrs={"class": "form-control", "placeholder": "请输入手机号"})
                             )
    password = forms.CharField(label="密码", max_length=64,
                               widget=forms.PasswordInput()
                               )
    re_password = forms.CharField(label="重复密码", max_length=64,
                                  widget=forms.PasswordInput())
    verify_sms = forms.CharField(label="验证码", max_length=6,
                                 widget=forms.TextInput(attrs={
                                     "v-model": "verify_sms"
                                 }))

    class Meta():
        model = User
        # 初始化所有字段
        fields = ["username", "email", "password", "re_password", "mobile", "verify_sms"]

    def clean_username(self):
        username = self.cleaned_data["username"]
        exists = User.objects.filter(username=username).exists()
        if exists:
            # raise ValidationError("用户名已存在")
            self.add_error("username", "用户名已存在")  # 将错误信息添加到username字段
        return username

    def clean_password(self):
        password = hash_password(self.cleaned_data["password"])
        return password

    def clean_re_password(self):
        # 获取数据只能获取在re_password 之前的数据，应为后面的数据还没有校验，所以获取不到
        # 有优先级顺序
        password = self.cleaned_data["password"]
        re_password = self.cleaned_data["re_password"]
        if check_password(re_password, password) == 1:
            raise ValidationError("两次密码不一致")
        return re_password

    def clean_mobile(self):
        mobile = self.cleaned_data.get("mobile")
        exists = User.objects.filter(mobile=mobile).exists()
        if exists:
            raise ValidationError("手机号重复注册")
        return mobile

    def clean_verify_sms(self):
        ver_code = self.cleaned_data["verify_sms"]
        # mobile = self.cleaned_data["mobile"]
        # 为了防止mobile不存在而报错抛出异常
        mobile = self.cleaned_data.get("mobile")
        # 创建redis 连接
        conn = get_redis_connection("ver_code")
        # 获取redis发送的验证码
        conn_code = conn.get("code_%s" % mobile)
        # 判断改手机号是否发送验证码
        if not conn_code:
            raise ValidationError("验证码失效或未发送")
        # 判断验证码是否正确
        if conn_code.decode() != ver_code.strip():
            raise ValidationError("验证码错误")
        return ver_code


class SendSMSModel(forms.ModelForm):
    mobile = forms.CharField(label="手机号", max_length=11,
                             validators=[RegexValidator(r'^1[3-9]\d{9}$', "手机号格式"), ],
                             # widget=forms.TextInput(attrs={"class": "form-control", "placeholder": "请输入手机号"})
                             )

    def __init__(self, request, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request

    def clean_mobile(self):
        mobile = self.cleaned_data["mobile"]
        # 校验用户名是否重复注册
        exists = User.objects.filter("mobile").exists()
        if exists:
            raise ValidationError("手机号重复注册")
        return mobile


class LoginForms(BootStrapForm, forms.ModelForm):
    username = forms.CharField(label="用户名或邮箱", max_length=20)
    password = forms.CharField(label="密码", max_length=18,
                               widget=forms.PasswordInput()
                               )
    image_code = forms.CharField(label="图片验证码", max_length=5,
                                 widget=forms.TextInput()
                                 )
    uuid = forms.CharField(label="uuid", max_length=20, widget=forms.HiddenInput())

    class Meta():
        model = User
        fields = ["username", "password", "image_code", "uuid"]


class LoginSMSForm(BootStrapForm, forms.ModelForm):
    mobile = forms.CharField(label="手机号", max_length=11,
                             validators=[RegexValidator(r'^1[3-9]\d{9}$', "手机号格式"), ],
                             # widget=forms.TextInput(attrs={"class": "form-control", "placeholder": "请输入手机号"})
                             )
    verify_sms = forms.CharField(label="验证码", max_length=6,
                                 widget=forms.TextInput(attrs={
                                     "v-model": "verify_sms"
                                 }))

    class Meta():
        model = User
        fields = ["mobile", "verify_sms"]
